package com.wingsfrog.ZcVideo;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

//import com.HkstreamNatNew.utils.CommonData;
//import com.HkstreamNatNew.utils.Imagedeal;
//import com.HkstreamNatNew.utils.LocalFile;
import com.wingsfrog.ZcVideo.Utility;
import com.wingsfrog.genius_rc.R;
import com.Player.Core.PlayerCore;
import com.Player.Source.SDKError;

public class VideoCanvas {
	public static final int MAX_RECONNECT_COUNT = 10;// 最多连接次数
	protected static final int STATE = 0;
	protected static final int RECONENT = 1;
	private static final String SEPERATER = "-";
	public boolean isShow = false;
	private RelativeLayout rlBackground;// 背景
	public ImageView imgVideo;// 视频显示
	// public TouchView imgVideo;

	// public TextView tvState;// 显示状态
	// public TextView tvDevName;// 显示状态

	public PlayerCore player;// 播放器
	// private int width;// 播放区域宽度
	// private int height;// 播放区域高度
	private int channel = -1;// 通道号
	private Context context;

	public String Name;// 设备名
	public String DevId;// 设备ID
	public String Address;// 地址
	public int Port;// 端口
	public String UserName;// 用户名
	public String Password;// 密码
	public int Channel;// 通道号
	public int MediaStreamType;// 播放的媒体类型
	public int StreamParserType;// 流解析类型
	public boolean hasPrepare = false;// 是否初始化
	private int ReconnectCount = 0;
	// private boolean isReconnecting = false;// 是否在重连之中
	public int tag;
	private boolean isFullScreen = false;// 是否全屏
	private boolean isAutoPlay = false;// 是否自动播放
	public boolean IsOpenSound = false;
	public TextView tvisRecordingStatus;
	boolean isStoping = false;// 正在停止中
	// private Imagedeal deal;
	private MotionEvent event;
	int index;
	boolean isScale = false;
	long datacount = 0;

	public ImageButton[] imgBtn = new ImageButton[8];
	private String imageDir;
	private boolean IsAudio;
	private int stream;
//	public Imagedeal deal;

	public VideoCanvas(int w, int h, Context c, boolean isScreenScale) {
		// width = w;
		// height = h;
		context = c;
		this.isScale = isScreenScale;
		rlBackground = new RelativeLayout(c);
		LayoutParams lp = new RelativeLayout.LayoutParams(w, h);
		lp.rightMargin = -2 * w;
		lp.bottomMargin = -2 * h;
		rlBackground.setLayoutParams(lp);
		//rlBackground.setBackgroundResource(R.drawable.video_gray_bg);
		rlBackground.setPadding(2, 2, 2, 2);

		imgVideo = new ImageView(c);
		// imgVideo = new TouchView(c, w, h);// 新改的

		imgVideo.setScaleType(isScreenScale ? ScaleType.FIT_CENTER
				: ScaleType.FIT_XY);
		// imgVideo.setScaleType(ScaleType.fin);
//		imgVideo.setImageResource(R.drawable.logo_add);
//		imgVideo.setBackgroundResource(R.drawable.video_gray_bg);
		imgVideo.setPadding(2, 2, 2, 2);
		// c.getResources().getColor(R.color.video_gray));
		// imgVideo.setImageResource(R.drawable.logo_add);
		imgVideo.setLayoutParams(new RelativeLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT));
		tvisRecordingStatus = new TextView(c);
		tvisRecordingStatus.setTextColor(ColorStateList.valueOf(0xffff0000));
		LayoutParams pRecording = new LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		pRecording.addRule(RelativeLayout.ALIGN_TOP);
		pRecording.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		tvisRecordingStatus.setPadding(0, 2, 7, 0);
		tvisRecordingStatus.setText("●REC");
		tvisRecordingStatus.setTextSize(18);
		tvisRecordingStatus.setLayoutParams(pRecording);
		setRecordingState(false);

		rlBackground.addView(imgVideo);

		// 添加状态栏布局
		// rlBackground.addView(tvState);
		// rlBackground.addView(tvDevName);
		rlBackground.addView(tvisRecordingStatus);
		player = new PlayerCore(context);

	}

	public MotionEvent getEvent() {
		return event;
	}

	// public void setEvent(MotionEvent event) {
	// this.event = event;
	// imgVideo.myOnTouch(event); // 如果用touchview则
	// }

	public void setScreenScale(boolean isScreenScale) {

		imgVideo.setScaleType(isScreenScale ? ScaleType.FIT_CENTER
				: ScaleType.FIT_XY);
		Log.i("isScreenScale", "isScreenScale : " + isScreenScale);
	}

	public boolean isIsOpenSound() {
		return IsOpenSound;
	}

	public void setIsOpenSound(boolean isOpenSound) {
		IsOpenSound = isOpenSound;
	}

	public void SetStreamParserType(int type) {
		// StreamParserType = type;
		// player = new PlayerCore(context, type);

	}

	// 使用播放前的初始化
	public void Prepare(String name, String deviceId, boolean isRealTime,
			String route,int stream) {
		Log.d("playcoreinit", "playcoreinit"); // 运行
		this.Name = name;
		player.SetPPtMode(false);
		player.SetOpenLog(true);
		player.CloseAudio();
		IsAudio = false;
		this.stream=stream;
		if (TextUtils.isEmpty(route)) {
			imageDir = getCurrentImageDir(name);
		}else
		imageDir = getCurrentImageDir(route);
		player.SetAlbumPath(imageDir);
		player.SetVideoPath(imageDir);
		this.DevId = deviceId;
		player.InitParam(deviceId, stream, imgVideo);
		//player.SetPlayModel(1);
		hasPrepare = true;
		ReconnectCount = 0;
	}

	public String getCurrentImageDir(String sub) {
//		String s = Config.UserImageDir
//				+ sub.replace(CommonData.ROUTE_SEPERATOR, "/") + "/";
		String s = "/sdcard/NewUMEye/Snap/";
		System.out.println("图片地址：" + s);
		return s;
	}

	public String getCurrentVideoDir(String sub) {
//		String s = Config.UserVideoDir
//				+ sub.replace(CommonData.ROUTE_SEPERATOR, "/") + "/";
		String s = "/sdcard/NewUMEye/Video/";
		System.out.println("录像地址：" + s);
		return s;
	}

	// public boolean isIsAudio() {
	// return IsAudio;
	// }

	public boolean setIsAudio(boolean open) {
		IsAudio = open;
		if (isPrepared()) {
			if (open) {

				player.OpenAudio();
			} else {
				player.CloseAudio();
			}
			return player.GetIsVoicePause();
		}
		return true;

	}

	public boolean IsAudio() {
		// IsAudio = isAudio;
		if (isPrepared()) {
			return player.GetIsVoicePause();
		}
		return false;

	}

	public boolean IsPPt() {
		// IsAudio = isAudio;
		if (isPrepared()) {
			return player.GetIsPPT();
		}
		return false;

	}

	public void setPPT(boolean isOpen) {
		// IsAudio = isAudio;
		if (isPrepared()) {
			if (isOpen) {
				player.StartPPTAudio();
			} else {
				player.StopPPTAudio();
			}
		}

	}

	public boolean isPlayed() {

		return isPrepared() ? (player.PlayCoreGetCameraPlayerState() == PlayLayout.PLAYING)
				: false;
	}

	public boolean getHasPrepare() {
		return hasPrepare;
	}

	public String getPlayFrameRate() {
		if (isPrepared() && isPlayed()) {
			return player.GetPlayFrameRate() + "fps" + " "
					+ player.GetFrameBitRate() + "kbps";
		} else {
			return "";
		}

	}

	public int[] getPlayRate() {
		int[] rate = new int[2];
		if (isPrepared() && isPlayed()) {

			rate[0] = player.GetPlayFrameRate();
			rate[1] = player.GetFrameBitRate();
			return rate;
		} else {
			return null;
		}

	}

	public boolean getVideoRecordState() {
		if (isPrepared()) {
			boolean isRecord = player.GetIsSnapVideo();
			setRecordingState(isRecord);
			return isRecord;
		} else {
			return false;
		}

	}

	public int getState() {
		if (isPrepared()) {
			int state = player.PlayCoreGetCameraPlayerState();
			Log.i("playCoreGetState", "playCoreGetState:" + state);
			if (state == 0) {
				return -1;
			}
			return state;
		} else {
			return SDKError.Statue_Ready;
		}

	}

	// 是否初始化播放地址
	public boolean isPrepared() {
		return player == null ? false : !TextUtils.isEmpty(player.DeviceNo);

	}

	public void release() {
		// player.DeviceNo = null;

	}

	/**
	 * 播放视频
	 * 
	 * @param channel
	 *            通道号
	 */
	public synchronized void Play() {
		// setScreenScale(false);
		if (isPrepared()) {
			if (isStoping) {
				return;
			}
			player.Play();
		}

	}

	/**
	 * 重新连接
	 */

	public synchronized void Reconnect() {
		new Thread() {

			@Override
			public void run() {
				if (isStoping) {
					return;
				}

				isStoping = true;
				VideoCanvas.this.stop();
				isStoping = false;
				handler.sendEmptyMessage(RECONENT);

			}
		}.start();

	}

	/**
	 * 返回重连次数
	 * 
	 * @return
	 */
	public int getReconnectCount() {
		return ReconnectCount;
	}

	public int getChannel() {
		return channel;
	}

	public synchronized void stop() {

		datacount = player.getDataCount() + datacount; // getDataCount
														// 必须在stop前调用 //
														// 停止后datacount就清空了

		player.Stop();
	}

	/**
	 * 停止播放
	 */
	public void Stop() throws Exception {
		if (player.GetIsSnapVideo()) {
			player.SetSnapVideo(false);
			setRecordingState(false);
		}
		if (player.GetIsPPT()) {
			player.StopPPTAudio();
		}
		if (!player.GetIsVoicePause()) {
			player.CloseAudio();
		}
		// imgVideo.setScaleType(ScaleType.FIT_CENTER);
		new Thread() {

			@Override
			public void run() {
				if (isStoping) {
					return;
				}

				isStoping = true;
				VideoCanvas.this.stop();
				isStoping = false;

				handler.sendEmptyMessage(STATE);

			}
		}.start();

	}

	public RelativeLayout getView() {
		return rlBackground;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == STATE) {

//				imgVideo.setImageResource(R.drawable.logo_add);
			} else if (msg.what == RECONENT) {
				player.Stop();

				player = new PlayerCore(context);
				player.SetPPtMode(false);
				player.SetOpenLog(false);
				if (IsAudio) {
					player.OpenAudio();
				} else {
					player.CloseAudio();
				}

				player.SetAlbumPath(imageDir);
				player.SetVideoPath(imageDir);
				player.InitParam(DevId,stream , imgVideo);
				//player.SetPlayModel(1);
				Play();
			}

		}
	};

	/**
	 * 设置位置
	 * 
	 * @param left
	 * @param top
	 */
	public void setPosition(int left, int top) {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
		p.leftMargin = left;
		p.topMargin = top;
		p.setMargins(left, top, -2 * p.width, -2 * p.height);
		// System.out.println("改变画面位置--->("+left+","+top+","+p.rightMargin+","+p.bottomMargin+")");
		rlBackground.setLayoutParams(p);
	}

	public int getLeft() {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
		return p.leftMargin;
	}

	public int getTop() {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
		return p.topMargin;
	}

	public int getWidth() {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
		return p.width;
	}

	public int getHeight() {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
		return p.height;
	}

	/**
	 * 重新设置尺寸
	 * 
	 * @param w
	 * @param h
	 */
	public void setSize(int w, int h) {
		RelativeLayout.LayoutParams p = (LayoutParams) rlBackground
				.getLayoutParams();
//		deal = Imagedeal.getdeal(imgVideo);
		p.width = w;
		p.height = h;
		p.rightMargin = -2 * w;
		p.bottomMargin = -2 * h;
		rlBackground.setLayoutParams(p);
	}

	/**
	 * 设置可视性
	 * 
	 * @param visible
	 */
	public void setVisibility(int visible) {
		rlBackground.setVisibility(visible);
		imgVideo.setVisibility(visible);
	}

	/**
	 * 设置高亮
	 * 
	 * @param isHightLight
	 */
	public void setHightLight(boolean isHightLight) {
		if (isHightLight) {
//			imgVideo.setBackgroundResource(R.drawable.video_blue_bg);
		} else {
//			imgVideo.setBackgroundResource(R.drawable.video_gray_bg);

		}
	}

	// public void setText(String text, String devName) {
	// tvState.setText(text);
	// tvDevName.setText(devName);
	// }
	//
	// public void setText(int text, int devName) {
	// tvState.setText(text);
	// tvDevName.setText(devName);
	// }
	//
	// public void setTextVisible(int visible) {
	// tvState.setVisibility(visible);
	// tvDevName.setVisibility(visible);
	// }

	public void setImgBtnVisible(int visible) {
		for (int i = 0; i < 8; i++) {
			imgBtn[i].setVisibility(visible);
		}
	}

	/**
	 * 查看视频是否可用（是否被隐藏)
	 * 
	 * @return 可用返回True，否则为false
	 */
	public boolean isEnable() {
		return rlBackground.getVisibility() == View.VISIBLE;
	}

	public void setFullScreen(boolean isFullScreen) {
		this.isFullScreen = isFullScreen;
		if (isFullScreen)
			rlBackground.setPadding(0, 0, 0, 0);
		else
			rlBackground.setPadding(1, 1, 1, 1);
	}

	/**
	 * 返回是否全屏
	 * 
	 * @return
	 */
	public boolean IsFullScreen() {
		return isFullScreen;
	}

	/**
	 * 设置是否自动播放
	 * 
	 * @param auto
	 */
	public void setAutoPlay(boolean auto) {
		isAutoPlay = auto;
	}

	/**
	 * 是否自动播放
	 * 
	 * @return
	 */
	public boolean IsAutoPlay() {
		return isAutoPlay;
	}

	public void setRecordingState(boolean isShow) {
		if (isShow) {
			tvisRecordingStatus.setVisibility(View.VISIBLE);
		} else {
			tvisRecordingStatus.setVisibility(View.GONE);
		}
	}

	/**
	 * 流量数据统计
	 * 
	 * @return
	 */
	public long getDatacount() {
		if (datacount == 0) {
			return player.getDataCount();
		}
		return datacount;
	}

	public void setDatacount(long datacount) {
		this.datacount = datacount;
	}

	public int firstLogin() {
		try {
			// player.Login();
			int i = 0;
			while (true) {

				Thread.sleep(1000);

				i++;
				// int state = player.GetPlayerState();
				// int state1 = player.GetLoginState();
				// Log.i("state", "state:" + state + "state1:" + state1);
				// if (state == SDKError.NET_ConnectingSucess) {
				// break;
				// } else if (state == SDKError.Statue_ConnectFail) {
				// break;
				// } else if (state == SDKError.Statue_PLAYING
				// || state1 == SDKError.Statue_LOGINSUCESS) {
				// break;
				// } else if (state == SDKError.NET_LOGIN_ERROR_USER) {
				// break;
				// } else if (state == SDKError.NET_Protocal_ERROR) {
				// break;
				// } else if (state == SDKError.NET_LOGIN_ERROR_PASSWORD) {
				// break;
				// } else if (i >= 40) {
				// // player.StopandRelease();
				// return -1;
				// }
			}
			// if (player.GetPlayerState() == SDKError.NET_ConnectingSucess
			// || player.GetPlayerState() == SDKError.Statue_PLAYING
			// || player.GetLoginState() == SDKError.Statue_LOGINSUCESS) {
			// int channel = player.GetMaxChannel();
			// // player.StopandRelease();
			// return channel;
			// }
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			// player.StopandRelease();
			e.printStackTrace();
		}
		// player.StopandRelease();
		return -1;

	}

	/**
	 * 全部停止
	 * 
	 */

	/**
	 * 截图
	 */
	public void setSnap() throws Exception {
		if (!Utility.isSDCardAvaible()) {
//			Toast.makeText(context, R.string.sdcard_unavaible,
//					Toast.LENGTH_SHORT).show();
			return;
		}
//		if (!LocalFile.CreateDirectory(imageDir)) {
//			Toast.makeText(context, R.string.snap_fail, Toast.LENGTH_SHORT)
//					.show();
//			return;
//		}
		player.SetAlbumPath(imageDir);
		player.SetSnapPicture(true);
		Toast.makeText(context, "图片成功保存到: " + imageDir,
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 截图
	 */
	public void setSnap(String path) throws Exception {
		if (!Utility.isSDCardAvaible()) {

			return;
		}
//		if (!LocalFile.CreateDirectory(path)) {
//			return;
//		}
		// player
		player.SetAlbumPath(path, "" + player.DeviceNo + ".jpg");
		player.SetSnapPicture(true);

		// deleteSameThumb(path, player.DeviceNo);
		// player.SetSnapPicture(true, player.DeviceNo + SEPERATER);

	}

	// 删除已经存在的缩略图
	void deleteSameThumb(String path, String deviceId) {
		File dir = new File(path);
		File[] listFile = dir.listFiles();
		for (int i = 0; i < listFile.length; i++) {
			File file = listFile[i];
			Log.w("listFile", "listFile:" + file.getName());
			if (file.getName().contains(SEPERATER)) {
				if (deviceId.equals(file.getName().split(SEPERATER)[0])) {
					file.delete();
					return;
				}
			}
		}

	}

	// 录像
	public boolean setVideo() throws Exception {

		if (!Utility.isSDCardAvaible()) {
			Toast.makeText(context, "sdcard unavailable",
					Toast.LENGTH_SHORT).show();
			return false;
		}
//		if (!LocalFile.CreateDirectory(imageDir)) {
//			Toast.makeText(context, "Can not access sdcard, snap failure", Toast.LENGTH_SHORT)
//					.show();
//			return false;
//		}
		if (player.GetIsSnapVideo()) {
			player.SetSnapVideo(false);
			setRecordingState(false);
			Toast.makeText(context,
					"录像成功保存到: " + imageDir,
					Toast.LENGTH_SHORT).show();
		} else {
			player.SetSnapVideo(true);
			setRecordingState(true);
			//Show.toast(context, R.string.video_stop_after_20);
		}
		return true;

	}

	/**
	 * 获取字符串
	 * 
	 * @param id
	 * @return
	 */
	String getString(int id) {

		return context.getString(id);

	}

}
